from datetime import datetime

from django.http import JsonResponse
from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView

from user.models import SysUser
from user.serializers import CustomTokenObtainPairSerializer, SysUserUpdateSerializer

from django.contrib.auth.hashers import make_password

class LoginView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

@method_decorator(csrf_exempt, name="dispatch")
class UserChangePasswordView(APIView):
    permission_classes = [AllowAny]  # ✅ 跟原来一致，不需要登录 token

    def post(self, request):
        data = request.data
        print("📥 收到密码修改数据:", data)

        user_id = data.get("id")
        old_password = data.get("oldPassword")
        new_password = data.get("newPassword")

        if not user_id or not old_password or not new_password:
            return Response({"code": 400, "msg": "参数不完整"})

        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            return Response({"code": 404, "msg": "用户不存在"})

        if user.password != old_password:
            return Response({"code": 403, "msg": "原密码错误！"})

        user.password = new_password
        user.update_time = datetime.now().date()
        user.save()

        return Response({"code": 200, "msg": "密码修改成功！"})
# Create your views here.
# class TestView(View):
#     def get(self,request):
#         userList_obj=SysUser.objects.all()  #从数据库中取出所有用户对象，返回的是一个 QuerySet 对象
#         # print(userList_obj,type(userList_obj))
#         userList_dict=userList_obj.values() # 转存字典，把 QuerySet 转换为字典格式
#         # print(userList_dict, type(userList_dict))
#         userList=list(userList_dict) # 把外层的容器转存List，转为真正的 Python 列表
#         print(userList, type(userList))
#         return JsonResponse({'code':200,'info':'测试！','data':userList}) #返回 JSON 响应

class JwtTestView(View):
    def get(self, request):
        try:
            user = SysUser.objects.get(username='python222', password='123456')
        except SysUser.DoesNotExist:
            return JsonResponse({'code': 400, 'msg': '用户不存在'})

        # 用 simplejwt 生成 token
        refresh = RefreshToken.for_user(user)
        access_token = str(refresh.access_token)
        refresh_token = str(refresh)

        return JsonResponse({
            'code': 200,
            'access_token': access_token,
            'refresh_token': refresh_token,
        })